<template>
  <div class="product-combine-container">
    <!-- 标题和操作按钮 -->
    <BasicInformation title="修改产品组装" :primary-actions="actions" @action="handleAction" />

    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="form-wrapper">
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-row :gutter="30">
          <el-col :md="8">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="组装日期" prop="date">
              <el-date-picker v-model="form.date" type="date" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
            </el-form-item>
          </el-col>
            <!-- 业务员 -->
            <el-col :md="8">
              <el-form-item label="业务员" prop="uid">
                <el-select
                  v-model="form.uid"
                  placeholder="请选择业务员"
                  style="width: 240px"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 库管员 -->
            <el-col :md="8">
              <el-form-item label="库管员" prop="skid">
                <el-select
                  v-model="form.skid"
                  placeholder="请选择库管员"
                  style="width: 240px"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 部门 -->
            <el-col :md="8">
              <el-form-item label="部门" prop="did">
                <el-select
                  v-model="form.did"
                  placeholder="请选择部门"
                  style="width: 240px"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>
      </el-card>

      <!-- BOM 信息 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">BOM 信息</span>
            <el-button type="primary" size="small" @click="bomDialogVisible = true">选择 BOM</el-button>
          </div>
        </template>
        <div v-if="bomDetails">
          <el-row :gutter="20">
            <el-col :md="8"><el-form-item label="BOM 编号"><span>{{ bomDetails.id }}</span></el-form-item></el-col>
            <el-col :md="8"><el-form-item label="BOM 名称"><span>{{ bomDetails.name }}</span></el-form-item></el-col>
            <el-col :md="8"><el-form-item label="产品名称"><span>{{ bomDetails.product.name }}</span></el-form-item></el-col>
          </el-row>
          <el-form-item label="产品仓库" prop="sids[0]">
            <el-select v-model="form.sids[0]" placeholder="请选择产品仓库" clearable>
              <el-option v-for="wh in warehouses" :key="wh.id" :label="wh.name" :value="wh.id" />
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-alert title="请先选择 BOM 后，再进行物料配置" type="info" show-icon />
        </div>
      </el-card>

      <!-- 商品清单 & 总装配数量 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">商品清单 & 总装配数量</span>
        </template>
        <el-form-item label="总装配份数" prop="count">
          <el-input-number v-model.number="form.count" :min="1" @change="onCountChange" style="width:100%" />
        </el-form-item>
        <el-table v-if="combinedItems.length" :data="combinedItems" border style="width:100%">
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="tax" label="税率" />
          <el-table-column label="即时库存">
            <template #default="{ $index }">
              {{ stocks[$index] }}
            </template>
          </el-table-column>
          <el-table-column label="仓库">
            <template #default="{ $index }">
              <el-select v-model="form.sids[$index]" placeholder="请选择仓库" clearable>
                <el-option v-for="wh in warehouses" :key="wh.id" :label="wh.name" :value="wh.id" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>

    <!-- BOM 选择对话框 -->
    <BOMSelectorDialog v-model:modelValue="form.bid" v-model:visible="bomDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ProCombine, BOM, Good } from '@/types/kc/CPZZ'
import BasicInformation from '@/public-view/BasicInformation.vue'
import BOMSelectorDialog from '@/basic-view/bom/BOMSelectorDialog.vue'
import request from '@/util/request'
import type { User } from '@/types/rs/User'
import type { Department } from '@/types/rs/Department'
import { useRoute } from 'vue-router'

const route = useRoute()
const code = route.params.code as string
const isEdit = ref(false)

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

const form = reactive<Partial<ProCombine>>({ id:0, code:'', bid:0, count:1, uid:0, did:0, skid:0, sids:[], date:new Date(), typeId:9 ,   createUser: user.user.name,updateUser: user.user.name,})
const formRef = ref<FormInstance>()
const userList = ref<User[]>([])
const deptList = ref<Department[]>([])
const warehouses = ref<{id:number;name:string}[]>([])
const bomDialogVisible = ref(false)
const bomDetails = ref<BOM|null>(null)
const stocks = ref<number[]>([])

const combinedItems = computed(() => {
  if (!bomDetails.value) return []
  const product = bomDetails.value.product
  const mats = bomDetails.value.material
  return [product, ...mats]
})

const minStock = computed(() => {
  const arr = stocks.value.slice(1)
  return arr.length?Math.min(...arr):0
})

const disabledDate = (time:Date)=>time.getTime()>Date.now()

const rules = reactive<FormRules>({
  code:[{required:true,message:'编号不能为空',trigger:'blur'}],
  date:[{required:true,message:'请选择日期',trigger:'change'}],
  uid:[{required:true,message:'请输入用户ID',trigger:'blur'}],
  skid:[{required:true,message:'请输入仓管人ID',trigger:'blur'}],
  did:[{required:true,message:'请输入部门ID',trigger:'blur'}],
  bid:[{required:true,message:'请选择 BOM',trigger:'change'}],
  count:[
    {required:true,message:'请输入装配数量',trigger:'blur'},
    {validator(_,v,cb){
      if(v<=0) return cb(new Error('装配数量必须大于0'))
      if(minStock.value&&v>minStock.value) return cb(new Error(`装配数量不能超过最小库存：${minStock.value}`))
      cb()
    },trigger:'blur'}
  ]
})

async function fetchStocks(){
  if(!bomDetails.value) return
  stocks.value = await Promise.all(form.sids.map(async(sid,idx)=>{
    if(!sid) return 0
    const gid = combinedItems.value[idx].id
    const r = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid',{params:{sid,gid}})
    return r.data.data?.stock||0
  }))
}

function onCountChange(){
  formRef.value?.validateField('count')
  fetchStocks()
}

onMounted(async()=>{
  const [u,d,w,codeRes] = await Promise.all([
    request.post('/per/user/getAll'),
    request.post('/per/dept/getAll'),
    request.get('basic/store/getAllStore'),
    request.post('xs/counter/addCode',{docType:'CPZZ'})
  ])
  userList.value = u.data.data
  deptList.value = d.data.data
  warehouses.value = w.data.data
  form.code = codeRes.data.data
  if(code){
    isEdit.value=true
    const res = await request.get('kc/proCombine/getOneProCombine',{params:{code}})
    const data = res.data.data
    console.log(res.data.data)
    Object.assign(form,{...data,date:data.date})
    const bomRes = await request.get('basic/BOM/getBOMById',{params:{id:data.bid}})
    bomDetails.value = bomRes.data.data
    await fetchStocks()
  }
})

watch(
  () => form.bid,
  async (newId) => {
    if (!isEdit.value) {
      form.sids = []
      stocks.value = []
      bomDetails.value = null
    }
    if (newId) {
      try {
        const res = await request.get('basic/BOM/getBOMById', { params: { id: newId } })
        bomDetails.value = res.data.data
        const mats = bomDetails.value.material || []
        if (!isEdit.value) {
          form.sids = [0, ...mats.map(() => 0)]
        }
        await fetchStocks()
      } catch {
        ElMessage.error('加载BOM详情失败')
      }
    }
  },
  { immediate: true }
)

watch(
  () => form.sids.slice(),
  async () => {
    if (!bomDetails.value || form.sids.length === 0) {
      stocks.value = []
      return
    }
    await fetchStocks()
  },
  { immediate: true }
)

const actions=[{name:'save',label:'保存',type:'primary'},{name:'reset',label:'重置',type:'warning'}]
function handleAction(act: string){act==='save'?submitForm():resetForm()}

async function submitForm(){
  await formRef.value?.validate()
  const api = isEdit.value?'updateProCombine':'addProCombine'
  const res = await request.post(`kc/proCombine/${api}`,JSON.parse(JSON.stringify(form)))
  if(res.data.code==200) ElMessage.success(res.data.message||(isEdit.value?'修改成功':'添加成功'))
  else ElMessage.error(res.data.message||'操作失败')
}

function resetForm(){
  formRef.value?.resetFields()
  Object.assign(form,{id:0,code:'',bid:0,count:1,uid:0,did:0,skid:0,sids:[],date:new Date(),typeId:9})
  isEdit.value=false
  bomDetails.value=null
  stocks.value=[]
  ElMessage.info('表单已重置')
}
</script>

<style scoped>
.product-combine-container{padding:20px}
.form-section{margin-bottom:20px}
.section-header{display:flex;justify-content:space-between;align-items:center}
.section-title{font-size:16px;font-weight:600}
.form-wrapper{max-width:800px;margin:auto}
</style>

